package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.demo.common.ErrorCode;
import com.example.demo.constant.CommonConstant;
import com.example.demo.entity.User;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.MD5Utils;
import com.example.demo.vo.UserLoginVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2025-01-27 20:52:34
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final JwtUtils jwtUtils;

    @Override
    public UserLoginVo login(String username, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = this.baseMapper.selectOne(queryWrapper);
        if (user.getStatus()==0){
            throw new BusinessException(ErrorCode.ACCOUNT_DISABLED);
        }
        if (ObjectUtils.isEmpty(user)) {
            throw new BusinessException(ErrorCode.ACCOUNT_NOT_EXIST);
        }
        if (!MD5Utils.verify(password, user.getPassword())) {
            throw new BusinessException(ErrorCode.PASSWORD_ERROR);
        }
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("username", user.getUsername());
        map.put("id", user.getId().toString());
        String token = jwtUtils.generateToken(map, CommonConstant.UserType.USER);
        return UserLoginVo.builder().
                token(token).
                build();
    }

    @Override
    public boolean checkUsernameExists(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);

        return this.baseMapper.selectOne(queryWrapper) != null;
    }
}
